//
//  BVPersonalViewController.m
//  AFNetworking
//
//  Created by 崔晋 on 2019/10/12.
//

#import "BVPersonalViewController.h"
#import "BVPersonalInfoTableViewCell.h"
#import "BVPersonalBasketballInfoTableViewCell.h"
#import "BVPersonalAllTipHeaderTableViewCell.h"
#import "BVService.h"
#import "SVProgressHUD.h"
#import "BVUserInfoModel.h"
#import "BVMetaModel.h"
#import "BVVideoPlayView.h"
#import "Masonry.h"
#import "BVFaceUploadImagePickerViewController.h"
#import "BVWorkoutModel.h"
#import "BVPersonalWorkoutTableViewCell.h"
#import "BVWorkoutDetailViewController.h"
#import "BVPopoverDateView.h"
#import "BVPopoverLocationVIew.h"

@interface BVPersonalViewController ()<UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (weak, nonatomic) IBOutlet UIView *fakeNavBar;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *navHeight;

@property (nonatomic, strong) BVPersonalInfoTableViewCell *personalInfoCell;
@property (nonatomic, strong) BVPersonalBasketballInfoTableViewCell *basketballInfoCell;
@property (nonatomic, strong) BVPersonalAllTipHeaderTableViewCell *allTipCell;

@property (nonatomic, strong) BVUserInfoModel *userInfoModel;

@property (nonatomic, strong) NSMutableArray<BVWorkoutModel *> *allDataSource;
@property (nonatomic, strong) NSMutableArray<BVWorkoutModel *> *dataSource;

@property (nonatomic, strong) BVPopoverDateView *dateView;
@property (nonatomic, strong) BVPopoverLocationVIew *locationView;

@end

@implementation BVPersonalViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadInitData];
}

- (void)setupViews {
    [self.tableView registerNib:[UINib nibWithNibName:@"BVPersonalWorkoutTableViewCell" bundle:[BVBundle bundleWithClass:self.class name:BV_BUNDLE_HOME_SCENE_MODULE]] forCellReuseIdentifier:@"BVPersonalWorkoutTableViewCell"];
    self.navHeight.constant = kNavigationBarHeight;
}

- (void)loadInitData {
    if ([BVUser shareInstance].model != nil) {
        [self.personalInfoCell configWithModel:[BVUser shareInstance].model];
        [self.basketballInfoCell configWithModel:[BVUser shareInstance].model];
        self.userInfoModel = [BVUser shareInstance].model;
    }
    [[BVService shareInstance] get:@"profile" param:@{} complete:^(BOOL success, id  _Nullable response) {
        if (success) {
            BVUserInfoModel *userModel = [[BVUserInfoModel alloc] initWithDictionary:response[@"data"] error:nil];
            self.userInfoModel = userModel;
            [BVUser shareInstance].model = userModel;
            [self.personalInfoCell configWithModel:[BVUser shareInstance].model];
            [self.basketballInfoCell configWithModel:[BVUser shareInstance].model];
        }else {
            [SVProgressHUD showErrorWithStatus:@"网络异常"];
        }
    }];
    [[BVService shareInstance] get:@"workout" param:@{} complete:^(BOOL success, id  _Nullable response) {
        if (success) {
            [self handleDataSourceWithArray:response[@"data"][@"results"]];
            if (self.dataSource.count == 0) {
                [self errorView];
            }
        }else {
            [self errorView];
        }
    }];
}

- (void)errorView {
    __weak typeof(self)weakSelf = self;
    [BVErrorView showWithType:BVErrorViewTypePersonal inView:self.view retryBlock:^{
        [weakSelf loadInitData];
    }];
}

- (void)handleDataSourceWithArray:(NSArray<NSDictionary *> *)dataList {
    self.allDataSource = [BVWorkoutModel arrayOfModelsFromDictionaries:dataList error:nil];
    self.dataSource = [BVWorkoutModel arrayOfModelsFromDictionaries:dataList error:nil];
    [self.tableView reloadData];
}

- (void)faceInputAct {
    BVFaceUploadImagePickerViewController *pickerC = [[BVFaceUploadImagePickerViewController alloc] init];
    pickerC.delegate = self;
    [self presentViewController:pickerC animated:YES completion:nil];
}


#pragma mark - image picker delegate
- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info {
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    if (image) {
        [SVProgressHUD showProgress:0];
        [picker dismissViewControllerAnimated:YES completion:nil];
        [[BVService shareInstance] postImageWithUrl:@"player/face"
                                              image:image
                                                key:@"face"
                                           progress:^(NSProgress * _Nonnull progress) {
            [SVProgressHUD showProgress:(double)progress.completedUnitCount / progress.totalUnitCount];
        }
                                           complete:^(BOOL success, id  _Nullable response) {
            if (success) {
                [SVProgressHUD showSuccessWithStatus:@"上传成功"];
            }else {
                [SVProgressHUD showErrorWithStatus:@"服务异常，请稍后重试"];
            }
        }];
    }
}

#pragma mark - tableview delegat and datasource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count + 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return self.personalInfoCell;
    }
    if (indexPath.row == 1) {
        return self.basketballInfoCell;
        
    }
    if (indexPath.row == 2) {
        return self.allTipCell;
    }
    BVPersonalWorkoutTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BVPersonalWorkoutTableViewCell" forIndexPath:indexPath];
    [cell configWithModel:self.dataSource[indexPath.row - 3]];
    __weak typeof(self)weakSelf = self;
    cell.playAct = ^{
        BVWorkoutDetailViewController *workoutVC = [[BVWorkoutDetailViewController alloc] initWithNibName:@"BVWorkoutDetailViewController" bundle:[BVBundle bundleWithClass:self.class name:BV_BUNDLE_HOME_SCENE_MODULE]];
        workoutVC.workoutModel = weakSelf.dataSource[indexPath.row - 3];
        workoutVC.hidesBottomBarWhenPushed = YES;
        [weakSelf.navigationController pushViewController:workoutVC animated:YES];
    };
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return [BVPersonalInfoTableViewCell cellHeight];
    }
    if (indexPath.row == 1) {
        return [BVPersonalBasketballInfoTableViewCell cellHeight];
    }
    if (indexPath.row == 2) {
        return [BVPersonalAllTipHeaderTableViewCell cellHeight];
    }
    return [BVPersonalWorkoutTableViewCell cellHeight];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}


- (NSArray<BVMetaArena *> *)locationDataSource {
    NSMutableArray<BVMetaArena *> *tempArray = [NSMutableArray array];
    for (BVWorkoutModel *model in self.allDataSource) {
        if (![tempArray containsObject:model.arena]) {
            [tempArray addObject:model.arena];
        }
    }
    return tempArray.copy;
}


#pragma mark - lazy load
- (BVPersonalInfoTableViewCell *)personalInfoCell {
    if (!_personalInfoCell) {
        _personalInfoCell = [[BVBundle bundleWithClass:self.class name:BV_BUNDLE_HOME_SCENE_MODULE] loadNibNamed:@"BVPersonalInfoTableViewCell" owner:nil options:nil].firstObject;
        __weak typeof(self)weakSelf = self;
        _personalInfoCell.faceInputAct = ^{
            [weakSelf faceInputAct];
        };
    }
    return _personalInfoCell;
}

- (BVPersonalBasketballInfoTableViewCell *)basketballInfoCell {
    if (!_basketballInfoCell) {
        _basketballInfoCell = [[BVBundle bundleWithClass:self.class name:BV_BUNDLE_HOME_SCENE_MODULE] loadNibNamed:@"BVPersonalBasketballInfoTableViewCell" owner:nil options:nil].firstObject;
    }
    return _basketballInfoCell;
}

- (BVPersonalAllTipHeaderTableViewCell *)allTipCell {
    if (!_allTipCell) {
        _allTipCell = [[BVBundle bundleWithClass:self.class name:BV_BUNDLE_HOME_SCENE_MODULE] loadNibNamed:@"BVPersonalAllTipHeaderTableViewCell" owner:nil options:nil].firstObject;
        __weak typeof(self)weakSelf = self;
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        [_allTipCell setDateBlock:^{
            [weakSelf.locationView removeFromSuperview];
            weakSelf.locationView = nil;
            weakSelf.dateView = [BVPopoverDateView showInView:window point:[weakSelf.allTipCell.dateButton convertPoint:CGPointMake(weakSelf.allTipCell.dateButton.width / 2.0, weakSelf.allTipCell.dateButton.height + 3) toView:window]];
            [weakSelf.dateView setSelectDay:^(NSInteger year, NSInteger month, NSInteger day) {
                weakSelf.dataSource = [weakSelf.allDataSource filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(BVWorkoutModel *_Nullable evaluatedObject, NSDictionary<NSString *,id> * _Nullable bindings) {
                    
                    if ([[evaluatedObject.enterAt.date formattedDateWithFormat:@"yyyy-MM-dd"] isEqualToString:[NSString stringWithFormat:@"%ld-%02ld-%02ld", year, month, day]]) {
                        return YES;
                    }else {
                        return NO;
                    }
                }]].mutableCopy;
                [weakSelf.tableView reloadData];
                [weakSelf.dateView removeFromSuperview];
                weakSelf.dateView = nil;
            }];
        }];
        [_allTipCell setLocationBlock:^{
            [weakSelf.dateView removeFromSuperview];
            weakSelf.dateView = nil;
            weakSelf.locationView = [BVPopoverLocationVIew showInView:window point:[weakSelf.allTipCell.locationButton convertPoint:CGPointMake(weakSelf.allTipCell.locationButton.width / 2.0, weakSelf.allTipCell.locationButton.height + 3) toView:window]];
            weakSelf.locationView.dataSource = [weakSelf locationDataSource];
            [weakSelf.locationView setSelectLocation:^(NSIndexPath * _Nonnull indexPath, BVMetaArena * _Nonnull model) {
                
                if (model.objectId.length == 0) {
                    weakSelf.dataSource = weakSelf.allDataSource.mutableCopy;
                }else {
                    weakSelf.dataSource = [weakSelf.allDataSource filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(BVWorkoutModel *  _Nullable evaluatedObject, NSDictionary<NSString *,id> * _Nullable bindings) {
                        if ([evaluatedObject.arena.objectId isEqualToString:evaluatedObject.arena.objectId]) {
                            return YES;
                        }
                        return NO;
                    }]].mutableCopy;
                }
                
                [weakSelf.tableView reloadData];
                [weakSelf.locationView removeFromSuperview];
                weakSelf.locationView = nil;
            }];
        }];
    }
    return _allTipCell;
}

- (NSMutableArray<BVWorkoutModel *> *)allDataSource {
    if (!_allDataSource) {
        _allDataSource = [NSMutableArray array];
    }
    return _allDataSource;
}


- (NSMutableArray<BVWorkoutModel *> *)dataSource {
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

@end
